//
//  PhotoViewController.m
//  CarLifes
//
//  Created by yu on 2017/6/14.
//  Copyright © 2017年 jpas. All rights reserved.
//

#import "PhotoViewController.h"
#import "ScanQRCodeViewController.h"
#import "TakePhotoViewController.h"
#import "MRProgress.h"
#import "LocationManager.h"

@interface PhotoViewController ()<UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UIImageView *logoImgView;

@property (weak, nonatomic) IBOutlet UIButton *scanQRCodeBtn;

@property (weak, nonatomic) IBOutlet UIButton *inputEquipIdBtn;

@property (nonatomic, strong) UIButton *selectBtn;

@property (weak, nonatomic) IBOutlet UITextField *equipIdTextField;
@property (weak, nonatomic) IBOutlet UILabel *lineView;

@property (weak, nonatomic) IBOutlet UILabel *tipLabel;


@property (weak, nonatomic) IBOutlet UIButton *installBtn;

@property (nonatomic, strong) UIScrollView *scrollView;

@end

@implementation PhotoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [IQKeyboardManager sharedManager].keyboardDistanceFromTextField = 120.0f;
    self.navigationItem.title = @"拍照";

    [self addAllConstraints];
    
    // 1:新装工单拍照
    if ([self.takePhotoType isEqualToString:@"1"]) {
        [self setLeftImageNamed:@"back_white" action:@selector(returnAction)];
    }
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    // 导航栏黑线隐藏
    [self.navigationController.navigationBar setBackgroundImage:[[UIImage alloc] init] forBarMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar setShadowImage:[[UIImage alloc] init]];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    // 导航栏黑线显示
    [self.navigationController.navigationBar setBackgroundImage:nil forBarMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar setShadowImage:nil];
}

- (void)setScanQRCodeBtn:(UIButton *)scanQRCodeBtn
{
    _scanQRCodeBtn = scanQRCodeBtn;
    _scanQRCodeBtn.selected = YES;
    self.selectBtn = _scanQRCodeBtn;
    
    [self isEquipIdLogin:NO];
    
    [_scanQRCodeBtn setTitleColor:kTextLightGrayColor forState:UIControlStateNormal];
//    [_scanQRCodeBtn setTitleColor:kTextBlackColor forState:UIControlStateSelected];
    if (@available(iOS 13.0, *)) {
        [_scanQRCodeBtn setTitleColor:UIColor.labelColor forState:UIControlStateSelected];
    } else {
        [_scanQRCodeBtn setTitleColor:UIColor.blackColor forState:UIControlStateSelected];
    }
}

- (void)setInputEquipIdBtn:(UIButton *)inputEquipIdBtn
{
    _inputEquipIdBtn = inputEquipIdBtn;
    [_inputEquipIdBtn setTitleColor:kTextLightGrayColor forState:UIControlStateNormal];
//    [_inputEquipIdBtn setTitleColor:kTextBlackColor forState:UIControlStateSelected];
    if (@available(iOS 13.0, *)) {
        [_inputEquipIdBtn setTitleColor:UIColor.labelColor forState:UIControlStateSelected];
    } else {
        [_inputEquipIdBtn setTitleColor:UIColor.blackColor forState:UIControlStateSelected];
    }
}

- (void)setInstallBtn:(UIButton *)installBtn {
    _installBtn = installBtn;
    if (@available(iOS 13.0, *)) {
        UIColor *loginColor = [UIColor colorWithDynamicProvider:^UIColor * _Nonnull(UITraitCollection * _Nonnull traitCollection) {
            if (traitCollection.userInterfaceStyle == UIUserInterfaceStyleLight) {
                return kBaseColor;
            } else {
                return kBaseColorDark20;
            }
        }];
        [_installBtn setBackgroundColor:loginColor];
    } else {
        [_installBtn setBackgroundColor:kBaseColor];
    }
}

#pragma mark - 扫描二维码进入拍照 -
- (IBAction)changeEnterBtnClick:(id)sender
{    
    UIButton *btn = (UIButton *)sender;
    if (btn != self.selectBtn)
    {   // 输入设备号
        self.selectBtn.selected = NO;
        self.selectBtn.titleLabel.font = SYSTEM_FONT(16);
        btn.selected = YES;
        btn.titleLabel.font = SYSTEM_FONT(23);
        self.selectBtn = btn;
    }
    else
    {   // 扫描二维码
        self.selectBtn.selected = YES;
    }
    
    if (self.inputEquipIdBtn.selected) {
        [self isEquipIdLogin:YES];
        [self.equipIdTextField becomeFirstResponder];
        //self.installBtn.userInteractionEnabled = NO;
        //self.installBtn.backgroundColor = [UIColor grayColor];
        self.inputEquipIdBtn.titleLabel.font = Font_NAME_SIZE(@"PingFangSC-Medium", 23);
        self.scanQRCodeBtn.titleLabel.font = Font_NAME_SIZE(@"PingFangSC-Medium", 16);
    } else {
        [self isEquipIdLogin:NO];
        [self.equipIdTextField resignFirstResponder];
        self.installBtn.userInteractionEnabled = YES;
        self.scanQRCodeBtn.titleLabel.font = Font_NAME_SIZE(@"PingFangSC-Medium", 23);
        self.inputEquipIdBtn.titleLabel.font = Font_NAME_SIZE(@"PingFangSC-Medium", 16);
        self.equipIdTextField.text = @"";
    }
}

- (void)isEquipIdLogin:(BOOL)isEquip
{
    if (isEquip)
    {
        self.equipIdTextField.hidden = NO;
        self.lineView.hidden = NO;
        self.tipLabel.hidden = YES;
    }
    else
    {
        self.equipIdTextField.hidden = YES;
        self.lineView.hidden = YES;
        self.tipLabel.hidden = YES;
    }
}

#pragma mark - 进入拍照系统 -

- (IBAction)enterCameraSystem:(id)sender
{
    [self.equipIdTextField resignFirstResponder];
    
    if (![LocationManager isLocationEnabled]) {// 用户拒绝开启定位权限
        [[[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"请在系统设置中开启定位服务(设置>隐私>定位服务>开启)，进行位置信息上传" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"去设置", nil] show];
        return;
    }
    
    if (self.inputEquipIdBtn.selected)
    {//输入设备号进入拍照系统
        if (!self.equipIdTextField.text.length) {
            [self showAlertView:@"设备号不能为空！"];
            return;
        }
        [self.requestTool eqNoLoginByEqno:self.equipIdTextField.text success:^(EqnoLoginModel *eqnoModel,int status) {
            PPLog(@"eqType = %@-%@",self.eqType,eqnoModel.eqId);
            switch (status) {
                case 0:
                {// 先查询照片
                    [self.requestTool queryEquipImgByEqId:eqnoModel.eqId show:NO success:^(NSArray *results) {
                        PPLog(@"Query img array == %ld",results.count);
                        TakePhotoViewController *tp = [[TakePhotoViewController alloc] init];
                        if (!results) {//上传提交
                            tp.uploadType = UploadImgTypeNormal;
                        } else {//补拍提交
                            tp.uploadType = UploadImgTypeSupplement;
                            tp.installInfo = results[0];
                            NSMutableArray *indexImg = [NSMutableArray array];
                            [results[1] enumerateObjectsUsingBlock:^(NSDictionary *result, NSUInteger idx, BOOL * _Nonnull stop) {
                                [indexImg addObject:result[@"type"]];
                            }];
                            
                            if (indexImg.count >= 3) {
                                [self showAlertView:@"信息已提交,正在审核!"];
                                return;
                            }
                            
                            tp.indexImg = indexImg;
                        }
                        
                        if ([self.takePhotoType isEqualToString:@"1"]) {//工单进入,要先判断型号是否一致
                            tp.takePhotoType = @"1";
                            
                            if (![eqnoModel.eqModel isEqualToString:self.eqType])
                            {// 点击的设备型号和实际设备型号不一致
                                UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"该设备型号和实际设备型号不匹配，请重新选择" preferredStyle:UIAlertControllerStyleAlert];
                                [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
                                    [self.navigationController popViewControllerAnimated:YES];
                                }]];
                                [self presentViewController:alert animated:YES completion:nil];
                                return;
                            }
                            
                        } else {//普通登录进入
                            tp.takePhotoType = @"0";
                        }
                        
                        tp.eqnoModel = eqnoModel;
                        [self.navigationController pushViewController:tp animated:YES];
                    } failure:^(NSError *error) {
                        
                    }];
                }
                    break;
                case 1:
                    [self showAlertView:@"信息已提交,正在审核!"];
                    break;
                case 2:
                    [self showAlertView:@"该设备号不存在!"];
                    break;
                case 3:
                {
                    if ([self.takePhotoType isEqualToString:@"1"]){
                        if (![eqnoModel.eqModel isEqualToString:self.eqType])
                        {// 点击的设备型号和实际设备型号不一致
                            UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"该设备型号和实际设备型号不匹配，请重新选择" preferredStyle:UIAlertControllerStyleAlert];
                            [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
                                [self.navigationController popViewControllerAnimated:YES];
                            }]];
                            [self presentViewController:alert animated:YES completion:nil];
                            return;
                        }
                    }
                    [self showAlertView:@"信息不全,请在平台完善信息!"];
                }
                    break;
                default:
                    break;
            }
            
        } failure:^(NSError *error) {
            PPLog(@"error = %@",error.description);
        }];
    }
    else
    {//扫描设备号二维码进入拍照系统
        ScanQRCodeViewController *sQR = [[ScanQRCodeViewController alloc] init];
        sQR.takePhotoType = self.takePhotoType;
        sQR.eqType = self.eqType;
        [self.navigationController pushViewController:sQR animated:YES];
    }
}

#pragma mark UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 1) {
        NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
        if ([[UIApplication sharedApplication] canOpenURL:url]) {
            [[UIApplication sharedApplication] openURL:url];
        }
    }
}

- (void)showAlertView:(NSString *)message
{
    UIAlertController *controller = [UIAlertController alertControllerWithTitle:nil message:message preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *OKAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
    
    [controller addAction:OKAction];
    [self presentViewController:controller animated:YES completion:nil];
}

- (IBAction)textFieldDidChange:(UITextField *)sender
{
//    if (sender == self.equipIdTextField) {
////        PPLog(@"%@",sender.text);
//        if (sender.text.length == 15) {
//            self.installBtn.userInteractionEnabled = YES;
//            self.installBtn.backgroundColor = kBaseColor;
//        }
//        else
//        {
//            self.installBtn.userInteractionEnabled = NO;
//            self.installBtn.backgroundColor = [UIColor grayColor];
//        }
//    }
}

//- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
//
//    if (textField == self.equipIdTextField) {
//        // 这里的if时候为了获取删除操作,如果没有次if会造成当达到字数限制后删除键也不能使用的后果.
//        if (range.length == 1 && string.length == 0)
//        {
//            return YES;
//        }
//        else if (self.equipIdTextField.text.length >= 15)
//        {
//            self.equipIdTextField.text = [textField.text substringToIndex:15];
//
//            return NO;
//        }
//    }
//    return YES;
//}

- (void)addAllConstraints
{
    _scrollView = [[UIScrollView alloc] init];
    //    _scrollView.alwaysBounceVertical = YES;
//    _scrollView.backgroundColor = [UIColor baseCLBlueColor];
    [self.view addSubview:_scrollView];
    
    _scrollView.sd_layout.spaceToSuperView(UIEdgeInsetsZero);
    
    [_scrollView sd_addSubviews:@[_logoImgView,_scanQRCodeBtn,_inputEquipIdBtn,_equipIdTextField,_lineView,_tipLabel,_installBtn]];
    
    CGFloat margin10 = 10; CGFloat margin15 = 15;
    CGFloat margin20 = 20; CGFloat margin30 = 30;
    
    _logoImgView.sd_layout
    .leftEqualToView(_scrollView)
    .rightEqualToView(_scrollView)
    .topEqualToView(_scrollView)
    .autoHeightRatio(0.63);
    
    _scanQRCodeBtn.sd_layout
    .leftSpaceToView(_scrollView, margin30)
    .topSpaceToView(_logoImgView, kAutoHeight(margin20*2))
    .heightIs(margin30)
    .widthIs(margin30*5);
    
    _inputEquipIdBtn.sd_layout
    .centerYEqualToView(_scanQRCodeBtn)
    .rightSpaceToView(_scrollView, margin30)
    .widthRatioToView(_scanQRCodeBtn, 1)
    .heightRatioToView(_scanQRCodeBtn, 1);
    
    _equipIdTextField.sd_layout
    .leftEqualToView(_scanQRCodeBtn)
    .topSpaceToView(_scanQRCodeBtn, kAutoHeight(margin20))
    .rightEqualToView(_inputEquipIdBtn)
    .heightIs(margin30);
    
    _lineView.sd_layout
    .leftEqualToView(_equipIdTextField)
    .rightEqualToView(_equipIdTextField)
    .topSpaceToView(_equipIdTextField, kAutoHeight(margin10))
    .heightIs(1);
    
    _tipLabel.sd_layout
    .leftEqualToView(_lineView)
    .rightEqualToView(_tipLabel)
    .topSpaceToView(_lineView, kAutoHeight(margin10))
    .heightIs(margin20);
    
    _installBtn.sd_layout
    .leftEqualToView(_tipLabel)
    .rightEqualToView(_lineView)
    .topSpaceToView(_tipLabel, margin15*2)
    .heightIs(45);
    
    [_scrollView setupAutoContentSizeWithBottomView:_installBtn bottomMargin:margin20*2];
}

- (void)returnAction
{
//    [[NSNotificationCenter defaultCenter] postNotificationName:@"kSendEqNoNotification" object:@"868120166146164" userInfo:nil];
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
